package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csxy.six.JwtUtils;
import com.csxy.six.R2;
import com.csxy.six.entity.*;
import com.csxy.six.exception.MyException;
import com.csxy.six.mapper.*;
import com.csxy.six.service.UserService;
import com.csxy.six.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private BlacklistMapper blacklistMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OssUtil ossUtil; // 注入OSS工具类

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    @Transactional
    public R2<User> register(User user, MultipartFile avatarFile) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new MyException(400, "用户名已存在");
        }

        // 检查邮箱是否已存在
        QueryWrapper<User> emailWrapper = new QueryWrapper<>();
        emailWrapper.eq("email", user.getEmail());
        if (userMapper.selectOne(emailWrapper) != null) {
            throw new MyException(400, "邮箱已被注册");
        }

        // 使用OSS上传头像
        if (avatarFile != null && !avatarFile.isEmpty()) {
            try {
                // 调用OSS工具上传头像
                String avatarUrl = ossUtil.uploadAvatar(avatarFile);
                user.setAvatar(avatarUrl); // 设置OSS返回的头像URL
            } catch (IOException e) {
                throw new MyException(500, "头像上传失败: " + e.getMessage());
            }
        }

        // 创建用户
        user.setStatus(1); // 正常状态
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);

        // 分配学生角色
        Role studentRole = roleMapper.findByName("STUDENT");
        if (studentRole == null) {
            throw new MyException(500, "系统配置错误：学生角色不存在");
        }

        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(studentRole.getId());
        userRole.setCreateTime(LocalDateTime.now());
        userRoleMapper.insert(userRole);

        // 返回用户信息（清除敏感信息）
        user.setPassword(null);
        return R2.ok(user).message("注册成功");
    }

    @Override
    public R2<User> login(String username, String password) {
        User user = userMapper.findByUsername(username);

        if (user == null) {
            throw new MyException(400, "用户不存在");
        }

        // 直接比较明文密码
        if (!user.getPassword().equals(password)) {
            throw new MyException(400, "密码错误");
        }

        // 检查用户是否在黑名单中
        if (blacklistMapper.checkIfBanned(user.getId()) > 0) {
            throw new MyException(403, "您已被拉入黑名单");
        }

        if (user.getStatus() == 0) {
            throw new MyException(403, "账号已被禁用");
        }

        // 获取用户角色
        List<Role> roles = userMapper.findRolesByUserId(user.getId());
        user.setRoles(roles);

        // 查找教师角色（如果存在）
        Optional<Role> teacherRole = roles.stream()
                .filter(role -> "TEACHER".equals(role.getName()))
                .findFirst();

        Long roleId = null;
        String roleName = null;

        // 优先使用教师角色，如果没有则使用第一个角色
        if (teacherRole.isPresent()) {
            roleId = teacherRole.get().getId();
            roleName = teacherRole.get().getName();
        } else if (!roles.isEmpty()) {
            roleId = roles.get(0).getId();
            roleName = roles.get(0).getName();
        }

        // 生成JWT token
        String token = jwtUtils.generateToken(user.getId(), user.getUsername(), roleId, roleName);

        // 设置token
        user.setToken(token);
        user.setPassword(null); // 清除密码

        return R2.ok(user);
    }

    @Override
    @Transactional
    public R2<User> createTeacher(User teacher) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(teacher.getUsername()) != null) {
            throw new MyException(400, "用户名已存在");
        }

        // 检查邮箱是否已存在
        QueryWrapper<User> emailWrapper = new QueryWrapper<>();
        emailWrapper.eq("email", teacher.getEmail());
        if (userMapper.selectOne(emailWrapper) != null) {
            throw new MyException(400, "邮箱已被注册");
        }

        // 创建教师账号
        teacher.setStatus(1); // 正常状态
        teacher.setCreateTime(LocalDateTime.now());
        userMapper.insert(teacher);

        // 分配教师角色
        Role teacherRole = roleMapper.findByName("TEACHER");
        if (teacherRole == null) {
            throw new MyException(500, "系统配置错误：教师角色不存在");
        }

        UserRole userRole = new UserRole();
        userRole.setUserId(teacher.getId());
        userRole.setRoleId(teacherRole.getId());
        userRole.setCreateTime(LocalDateTime.now());
        userRoleMapper.insert(userRole);

        // 返回用户信息（清除敏感信息）
        teacher.setPassword(null);
        return R2.ok(teacher).message("教师账号创建成功");
    }
}